"ui";

showLoginUI();
ui.statusBarColor("#000000")

//显示登录界面
function showLoginUI() {
  ui.layout(
    <frame>
      <vertical>
        <appbar>
          <toolbar id="toolbar" title="咪咕阅读打卡" />
        </appbar>
        <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" />
        <linear>
          <text w="150" h="20" text="开屏广告时长:" textColor="black" textSize="15" marginLeft="10" marginTop="25" />
        </linear>
        <linear>
          <input id="launchAdDuration" w="*" h="40" inputType="number" marginLeft="10" textSizeHint="11">5</input>
        </linear>
        <linear>
          <text w="150" h="20" text="页面加载时长:" textColor="black" textSize="15" marginLeft="10" marginTop="25" />
        </linear>
        <linear>
          <input id="loadDataDuration" w="*" h="40" inputType="number" marginLeft="10" textSizeHint="11">2</input>
        </linear>
        <linear>
          <text w="150" h="20" text="阅读时长:" textColor="black" textSize="15" marginLeft="10" marginTop="25" />
        </linear>
        <linear>
          <input id="readDuration" w="*" h="40" inputType="number" marginLeft="10" textSizeHint="11">16</input>
        </linear>

        <linear gravity="center">
          <button id="statTask" style="Widget.AppCompat.Button.Colored" marginLeft="40" marginRight="40" w="*" text="开始执行" />
        </linear>
      </vertical>
    </frame>
  );
  ui.statTask.on("click", () => {
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
      toast("请先开启无障碍服务！");
      return;
    }
    threads.start(function () {
      //在新线程执行的代码
      startTask();
    });
  });
  ui.autoService.on("check", function (checked) {
    // 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
    if (checked && auto.service == null) {
      app.startActivity({
        action: "android.settings.ACCESSIBILITY_SETTINGS"
      });
    }
    if (!checked && auto.service != null) {
      auto.service.disableSelf();
    }
  });

  // 当用户回到本界面时，resume事件会被触发
  ui.emitter.on("resume", function () {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
  });
}

var packageName = "com.ophone.reader.ui";

function startTask() {
  auto.waitFor();
  const WIDTH = Math.min(device.width, device.height);
  const HEIGHT = Math.max(device.width, device.height);
  setScreenMetrics(WIDTH, HEIGHT);
  launchApp();
  waitForActivity("com.cmread.bplusc.bookshelf.LocalMainActivity");
  sleepTime(ui.launchAdDuration.text());

  tabbarIndexOf(1);

  /// 先执行签到
  clickTextCenter("签到领书券");
  clockIn();

  tabbarIndexOf(2);

  /// 打开免费选项
  clickTextCenter("免费");

  /// 打开置顶的免费小说
  let chooseBook = className("android.widget.ImageView").depth(25).drawingOrder(1).findOne();
  clickCenter(chooseBook);

  if (text("免费畅读").exists()) {
    clickTextCenter("免费畅读");
  } else {
    clickTextCenter("继续阅读");
  }

  //// 翻页
  swipePage();

  backToPrePage(1);
  /// 根据是否弹出加入书架的选项进行处理
  if (id("button_cancel").exists()) {
    clickIdCenter("button_cancel");
  }
  backToPrePage(2);

  clickTextCenter("更多福利");

  alert("任务完成，看看完成状态吧");

  exit();
}

/// index: 1、书架；2、图书；3、听书；4、发现；5、我的
function tabbarIndexOf(index) {
  let tabbarBtn = className("android.widget.FrameLayout").depth(11).clickable(true).drawingOrder(index).findOne();
  if (tabbarBtn) {
    clickCenter(tabbarBtn);
  }
}

//let pageContainer = className("android.widget.LinearLayout").depth(1).findOne();
function swipePage() {
  var startDate = new Date();
  do {
    sleepTime(random(15, 25));
    swipe(device.width * 7 / 8, device.height * 7 / 8, device.width / 2, device.height / 2, 200);
    var endDate = new Date();
  } while ((endDate.getTime() - startDate.getTime()) / 1000 < ui.readDuration.text() * 60);
};

function clickCenter(widget) {
  if (!widget)
    return false;
  let rect = widget.bounds();
  click(rect.centerX(), rect.centerY());
  sleepTime(ui.loadDataDuration.text());
};

function clickSelectorCenter(selector) {
  if (!selector)
    return false;
  let widget = selector.findOne(2000);
  return clickCenter(widget);
};

function clickTextCenter(str) {
  if (!str)
    return false;
  return clickSelectorCenter(text(str));
};

function clickIdCenter(idStr) {
  if (!idStr)
    return false;
  return clickSelectorCenter(id(idStr));
};

function launchApp() {
  launch(packageName);
  device.vibrate(500);
};

function sleepTime(second) {
  sleep(second * 1000);
};
/// param(level): 返回的层数
function backToPrePage(level) {
  for (let index = 0; index < level; index++) {
    back();
    sleepTime(1.5);
  }
};

function clockIn() {
  if (text("签").exists()) {
    clickTextCenter("签");
  }
  sleepTime(1.5);
  back();
};
